package com.freewater.javabase.demo.network.http;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;

public class URLDownBinaryFile {
    public static void main(String[] args) throws IOException {
        URL url = new URL("https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png");
        download(url);
    }

    public static void download(URL url) throws IOException {
        final URLConnection urlConnection = url.openConnection();
        final String contentType = urlConnection.getContentType();
        final int contentLength = urlConnection.getContentLength();
        if ((contentType != null && contentType.startsWith("text/")) || contentLength == -1) {
            throw new IOException("this is not a binary file");
        }
        try (BufferedInputStream bis = new BufferedInputStream(urlConnection.getInputStream())) {
            byte[] data = new byte[contentLength];
            int offset = 0;
            while (offset < contentLength) {
                int bytesRead = bis.read(data, offset, contentLength - offset);
                if (bytesRead == -1) {
                    break;
                }
                offset += bytesRead;
            }
            if (offset != contentLength) {
                throw new IOException("Only read " + offset + " bytes; Expected "
                        + contentLength + " bytes");
            }

            final String file = url.getFile();
            final int index = file.lastIndexOf("/");
            final String fileName = "." + file.substring(index);
            writeFile(fileName, data);
        }
    }

    private static void writeFile(String fileName, byte[] bytes) throws IOException {
        File file = new File(fileName);
        try (final FileOutputStream fileOutputStream = new FileOutputStream(file);
             BufferedOutputStream os = new BufferedOutputStream(fileOutputStream)) {
            os.write(bytes);
            os.flush();
            System.out.println("file downloaded, size: " + bytes.length + ", location: " + file.getAbsolutePath());
        }
    }
}
